package com.hyp.pay.UI.Home.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.hyp.pay.R;
import com.hyp.pay.UI.Home.activity.FaceActivity;
import com.hyp.pay.http.Constants;
import com.hyp.pay.network.NetBroadcastReceiver;
import com.hyp.pay.network.NetEvent;
import com.hyp.pay.utils.FileCacheUtils;
import com.hyp.pay.utils.NetWorkUtils;
import com.hyp.pay.weight.ErrorLayout;

public class WebViewActivity extends Activity implements NetEvent ,View.OnClickListener{

    /**
     * 网络状态
     */
    private int netMobile;

    /**
     * 这里保存一个值用来判断网络是否经历了由断开到连接
     */
    private boolean isNetChanges;

    /**
     * 监控网络的广播
     */
    private NetBroadcastReceiver netBroadcastReceiver;


    private String urlPath;
    private WebSettings webSettings;
    private final String ERROR_HTML = "<html><body bgcolor='#1f1f1f'><font color='#ffffff' size='3'>找不到页面，请检查网络连接!</font></body></html>";
    private String title;
    private WebView mWebview;
    private ErrorLayout mErrorLayout;

    //    private String Host="http://192.168.1.123:8888/hyqPayService/";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        mWebview = (WebView) findViewById(R.id.webView);
        mErrorLayout= (ErrorLayout) findViewById(R.id.error_layout);
        mErrorLayout.setOnLayoutClickListener(this);
        Intent intent = getIntent();
        if (intent != null) {
            urlPath = intent.getStringExtra(Constants.WEB_VIEW_URL_PATH);
        }


        initWebView();
    }

    /**
     * 初始化WebView设置
     */
    private void initWebView() {
        webSettings = mWebview.getSettings();
        mWebview.setBackgroundColor(getResources().getColor(R.color.window_bg));// 设置默认背景颜色，否则有时会出现白色背景
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setJavaScriptEnabled(true);  //设置webview支持js
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
        webSettings.setAppCacheEnabled(true);//开启 Application Caches 功能
        webSettings.setJavaScriptEnabled(true);
        //设置本地调用对象及其接口Q
        //设置本地调用对象及其接口Q
        mWebview.addJavascriptInterface(new JsInteraction(this), "Oulijun");

        int screenDensity = getResources().getDisplayMetrics().densityDpi;
        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
        switch (screenDensity) {
            case DisplayMetrics.DENSITY_LOW:
                zoomDensity = WebSettings.ZoomDensity.CLOSE;
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
                break;
            case DisplayMetrics.DENSITY_HIGH:
                zoomDensity = WebSettings.ZoomDensity.FAR;
                break;
        }
        webSettings.setDefaultZoom(zoomDensity);// 按照屏幕密度比例缩放
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);// 支持内容重新布局
        webSettings.setLoadWithOverviewMode(true);// 适应屏幕
        /**
         * urlPath 为空加载默认erro网页
         */
        if (TextUtils.isEmpty(urlPath)) {
            mWebview.loadData(ERROR_HTML, "text/html; charset=UTF-8", null);
        } else {
            Log.i("olj", urlPath);
            mWebview.loadUrl(urlPath);

        }


        mWebview.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

            }
        });

        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.startsWith("tel:")) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                } else {

                    mWebview.loadUrl(url);
                    if (!isNetChanges){
                        mErrorLayout.setVisibility(View.VISIBLE);
                        mErrorLayout.setState(ErrorLayout.NETWORK_ERROR);
                    }
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                webSettings.setBlockNetworkImage(false);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                mWebview.loadData(ERROR_HTML, "text/html; charset=UTF-8", null);
            }
        });


    }

    @Override
    public void onNetChange(int netMobile) {

    }

    @Override
    public void onClick(View view) {

    }

    public class JsInteraction {
        Context context;
        public JsInteraction(Context c) {
            context= c;
        }

        @JavascriptInterface
        public void startScan(String charge, String userid) {   //提供给js调用的方法
//            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            Log.i("olj","!!!!!1111111111111111111111111111111111111111111111");
            Log.i("olj","!!!!!1111111111111111111111111111111111111111111111"+charge);
            Log.i("olj","!!!!!1111111111111111111111111111111111111111111111"+userid);
            Intent intent = new Intent(WebViewActivity.this, FaceActivity.class);
            intent.putExtra("charge", charge);
            intent.putExtra("userid", userid);
            startActivity(intent);

//            Intent intent=new Intent(HomeActivity.this, TestScanActivity.class);
//            intent.putExtra("charge",charge);
//            intent.putExtra("userid",userid);
//            startActivityForResult(intent, 0x1);
        }

        @JavascriptInterface
        public void startgoPay(String url){

            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);

        }

        @JavascriptInterface
        public void clearData(){

            Log.i("olj","222222222222222222222222222222222222222222222222222");
//            FileCacheUtils.clearAppUserData(mContext,"com.hyp.pay");
            FileCacheUtils.cleanApplicationData(WebViewActivity.this,"com.hyp.pay");

        }

        @JavascriptInterface
        public void update() {   //提供给js调用的方法
//            mWebview.loadUrl(beforeUrl);//调用js中的函数：showInfoFromJava(msg)
        }
    }
}
